from flask_restful import reqparse,Api,Resource,request,marshal
from flask import Blueprint,jsonify,json,g,Response
from werkzeug.security import generate_password_hash,check_password_hash
from models import db
from models.users import *
import random,redis,string,uuid
from celery_tasks.tasks.task import sms_code
from common.utlis.name_list import *
from common.utlis.login_utlis import login_required
from common.utlis.qiniu_token import qiniu_token


from captcha.image import ImageCaptcha


from common.utlis.jwt_util import _generate_token


user_bp = Blueprint('ubp', __name__, url_prefix='/user')
api = Api(user_bp)


class SenSmsCode(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('mobile')
        args = parser.parse_args()
        mobile = args.get('mobile')
        code = random.randint(10000,99999)
        print("验证码>>", code)
        sms_code.delay(mobile,code)

        rds = redis.Redis(host="localhost", port=6379, password=123, db=2)
        rds.set('sms_%s'%mobile, code, ex=200)
        return jsonify(message='短信验证码发送成功', code=200)


class UserRegister(Resource):
    rds = redis.Redis(host="localhost", port=6379, password=123, db=2)
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username')
        parser.add_argument('password')
        parser.add_argument('password2')
        parser.add_argument('mobile')
        parser.add_argument('code')
        args = parser.parse_args()
        username = args.get('username')
        password = args.get('password')
        password2 = args.get('password2')
        mobile = args.get('mobile')
        code = args.get('code')


        if password != password2:
            return jsonify(message='两次密码不一样', code=400)
        origin_sms_code = self.rds.get('sms_%s'%mobile)
        print('验证码...', code, origin_sms_code)
        if not origin_sms_code:
            return jsonify(message='短信验证码已过期', code=400)
        if code != origin_sms_code.decode('utf-8'):
            return jsonify(message='验证码错误', code=401)

        try:
            hash_pwd = generate_password_hash(password)
            user = User(username=username,password=hash_pwd, mobile=mobile)
            db.session.add(user)
            db.session.commit()
            return jsonify(message='注册用户成功', code=200)
        except Exception as e:
            print('错误>>', e)
            return jsonify(message='注册用户失败', code=400)


class UserLogin(Resource):

    # 获取图片验证码
    def get(self):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('uuid')
            args = parser.parse_args()
            uuid = args.get('uuid')
            # 生成验证码
            salt = "".join(random.sample(string.ascii_letters + string.digits,4))

            # 生成验证码
            img = ImageCaptcha()
            image = img.generate(salt)

            key = "image_sms%s"%uuid
            redis_con = redis.Redis(host='localhost', port=6379, db=0, password='123')
            redis_con.set(key,salt,ex= 60 * 5)

            return Response(image,mimetype="image/jpeg")
        except Exception as e:
            print("错误信息", e)
            return jsonify(message="服务器错误！", code=500)
    # 登录的视图
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username')
        parser.add_argument('password')
        parser.add_argument('uuid')
        parser.add_argument('img_code')
        args = parser.parse_args()
        username = args.get('username')
        password = args.get('password')
        uuid = args.get('uuid')
        img_code = args.get('img_code')
        print('uuid', uuid)
        try:
            redis_con = redis.Redis(host='localhost', port=6379, db=0, password='123')
            code = 'image_sms%s'%uuid
            sms_code = redis_con.get(code)
            user = User.query.filter_by(username=username).first()
            print('用户>>', user)
            if not user:
                return jsonify(message='该用户不存在', code=204)
            print('sms_code',sms_code)
            if sms_code:
                if img_code == sms_code.decode():
                    return jsonify('图片验证码验证成功', uuid=code)
            else:
                return jsonify(message='验证码过期')

            if check_password_hash(user.password,password):
                data = {
                    'id': user.id,
                    'name': user.username
                }
                token = _generate_token(data, is_refresh=False)
                print('token》》》', token)
                data_ = {
                    'token':token
                }

                return jsonify(message='登录成功', code=200, data=data_)
            return jsonify(message='密码错误', code=204)
        except Exception as e:
            print('错误', e)
            return jsonify(message='登录失败', code=400)

# 书籍的视图
class BooksInfo(Resource):
    # 添加书籍信息
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('book_name')
        parser.add_argument('book_auther')
        parser.add_argument('book_price')
        args = parser.parse_args()
        book_name = args.get('book_name')
        book_auther = args.get('book_auther')
        book_price = args.get('book_price')
        try:
            auther = Auther(book_name=book_name,book_auther=book_auther,book_price=book_price)
            db.session.add(auther)
            db.session.commit()
            return jsonify(message='添加书籍成功', code=200)
        except Exception as e:
            print('错误>>', e)
            return jsonify(message='添加书籍失败', code=400)
    # 查询所有的书籍
    def get(self):
        try:
            books = Books.query.all()
            data = json.loads(json.dumps(marshal(books,book_fields)))
            for i in data:
                auther = Auther.query.filter_by(id=i["book_auther"]).first()
                i["name"] = auther.name
            return jsonify(message='查询书籍成功', code=200, data=data)
        except Exception as e:
            print('错误>>', e)
            return jsonify(message='查询书籍失败', code=400)


# 作者的视图
class AutherList(Resource):
    # 添加作者信息
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('book_name')
        parser.add_argument('book_auther')
        parser.add_argument('book_price')
        args = parser.parse_args()
        book_name = args.get('book_name')
        book_auther = args.get('book_auther')
        book_price = args.get('book_price')
        try:
            auther = Auther(book_name=book_name,book_auther=book_auther,book_price=book_price)
            db.session.add(auther)
            db.session.commit()
            return jsonify(message='添加作者成功', code=200)
        except Exception as e:
            print('错误>>', e)
            return jsonify(message='添加作者失败', code=400)
    # 查询所有的作者
    def get(self):
        try:
            auther = Auther.query.all()
            data = json.loads(json.dumps(marshal(auther,auther_fields)))
            return jsonify(message='查询作者成功', code=200, data=data)
        except Exception as e:
            print('错误>>', e)
            return jsonify(message='查询作者失败', code=400)


# 查询作者下的所有书籍
class BooksOne(Resource):
    def get(self,id):
        try:
            books = Auther.query.filter_by(id=id).first()
            print("kkk",books)
            data = marshal(books.books_id,book_fields)
            return jsonify(message='查询成功', code=200, data=data)
        except Exception as e:
            print('错误>>', e)
            return jsonify(message='查询失败', code=400)

# 注册
class RegisterInfo(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username')
        parser.add_argument('password')
        args = parser.parse_args()
        username = args.get('username')
        password = args.get('password')
        try:
            user = User(username=username, password=password)
            db.session.add(user)
            db.session.commit()
            return jsonify(message='注册成功', code=200)
        except Exception as e:
            print('错误>>', e)
            return jsonify(message='注册失败', code=204)

# 登录
class LoginInfo(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username')
        parser.add_argument('password')
        args = parser.parse_args()
        username = args.get('username')
        password = args.get('password')
        try:
            user = User.query.filter_by(username=username).first()
            if not user:
                return jsonify(message='没有此用户', code=400)
            pwd = User.query.filter_by(password=password).first()
            if not pwd:
                return jsonify(message='密码输入错误', code=204)
            return jsonify(message='登录成功', code=200)
        except Exception as e:
            print('错误>>', e)
            return jsonify(message='登录失败', code=204)


class UserInfo(Resource):
    def get(self):
        user = User.query.all()
        users = json.loads(json.dumps(marshal(user,user_fields)))
        return jsonify(message='获取用户信息成功', code=200, data=users)


# 获取七牛云token
class get_quniu_token(Resource):
    @login_required
    def get(self):
        try:
            user_id = g.user_id
            if not user_id:
                return jsonify(msg='请重新登录!', code=200)
            token = qiniu_token()
            return jsonify(message='成功', data=token)
        except Exception as e:
            print('错误信息', e)
            return jsonify(message='服务器错误', code=500)

api.add_resource(SenSmsCode, '/sms_code')
api.add_resource(UserRegister, '/register_user')
api.add_resource(UserLogin, '/login')

# 书籍的路由
api.add_resource(BooksInfo, '/books')

# 作者的路由
api.add_resource(AutherList, '/auther')

api.add_resource(BooksOne, '/info/<int:id>')

# 注册用户接口2
api.add_resource(RegisterInfo, '/register')
# 登录用户的接口2
api.add_resource(LoginInfo, '/logins')

# 获取用户的信息
api.add_resource(UserInfo, '/user_info')


# 七牛云上传
api.add_resource(get_quniu_token ,'/uptoken')
